package com.junjie.checkin.controller;

import com.junjie.checkin.response.Result;
import com.junjie.checkin.response.ResultStatus;
import com.junjie.checkin.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * 通用的接口
 */
@RestController
@RequestMapping("/admin/common")
@Slf4j
public class CommonController {
    @Autowired
    private AliOssUtil aliOssUtil;
    /**
     * 文件上传
     * @param file 文件数据
     * @return 统一响应数据,返回文件访问路径
     */
    @PostMapping("/upload")
    public Result<String> upload(MultipartFile file){
        log.info("文件上传：{}",file);
        try {
            //原始文件名
            String originalFilename = file.getOriginalFilename();
            //截取文件名后缀
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            //通过UUID重新生成文件名
            String objectName = UUID.randomUUID().toString() + extension;
            //filePath 为上传到OSS服务器上的路径
            String filePath = aliOssUtil.upload(file.getBytes(), objectName);
            return Result.getResult(ResultStatus.OK,filePath);
        } catch (IOException e) {
            log.error("文件上传失败: {}" ,e);
        }

        return Result.getResult(ResultStatus.UPLOAD_FAILED);
    }
}
